//////////////////////////////////////////////////////////
var canvas;
var ctx;
var canvas_offset;
var nums = new Array(10, 15, 2, 17, 3, 19, 7, 16, 8, 11, 14, 9, 12, 5, 20, 1, 18, 4, 13, 6);
var selectedNums = new Array();
var deg = 360/nums.length;
dartImages = new Array();
var dartImage = new Image();
dartImage.src = "images/dart.png";
dartImages[dartImages.length] = {image:dartImage,xscale:2/3,yscale:9/10};
var dartImage2 = new Image();
dartImage2.src = "images/dart2.png";
dartImages[dartImages.length] = {image:dartImage2,xscale:1/4,yscale:9/10};
var dartImage3 = new Image();
dartImage3.src = "images/dart3.png";
dartImages[dartImages.length] = {image:dartImage3,xscale:1/3,yscale:2/3};

// center
var cx,cy;
var poly_num0 = 200;
var poly_num1 = 201;

var rad_from;
var rad_to;
var poly_x = new Array();
var poly_y = new Array();
var darts_board_width;
var darts_board_height;
var darts_hook = "default_hook";
Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] == value) {
			return true;
		}
	}
	return false;
};
Array.prototype.removeByValue = function(val) {
    for(var i=0; i<this.length; i++) {
        if(this[i] == val) {
            this.splice(i, 1);
            break;
        }
    }
}
//////////////////////////////////////////////////////////
function pointInPolygon(x, y, sector_i, rad_i) {
  var xp,yp;

  if (rad_i >= 2) {
    xp = poly_x[rad_i*20 + sector_i];
    yp = poly_y[rad_i*20 + sector_i];
  } else {
    if (rad_i == 1) {
      xp = poly_x[poly_num1];
      yp = poly_y[poly_num1];
    }
    if (rad_i == 0) {
      xp = poly_x[poly_num0];
      yp = poly_y[poly_num0];
    }
  }

  npol = xp.length;
  j = npol - 1;
  var c = 0;
  for (i=0; i<npol; i++){
      if ((((yp[i]<=y) && (y<yp[j])) || ((yp[j]<=y) && (y<yp[i]))) &&
          (x > (xp[j] - xp[i]) * (y - yp[i]) / (yp[j] - yp[i]) + xp[i])) {
        c = !c
      }
      j = i;
  }
  return c;
}
//////////////////////////////////////////////////////////
function drawSector(ctx, fillStyle, sector_i, rad_i) {
   ctx.fillStyle = fillStyle;

var degree1 = (sector_i+0) * deg + deg/2 + 0.5;
var degree2 = (sector_i+1) * deg + deg/2 - 0.5;
var rl = rad_to[rad_i];
var rs = rad_from[rad_i];

var x1 = rl * Math.cos( degree2 * Math.PI / 180);
var y1 = rl * Math.sin( degree2 * Math.PI / 180);
var x2 = rl * Math.cos( degree1 * Math.PI / 180);
var y2 = rl * Math.sin( degree1 * Math.PI / 180);
var x3 = rs * Math.cos( degree1 * Math.PI / 180);
var y3 = rs * Math.sin( degree1 * Math.PI / 180);
var x4 = rs * Math.cos( degree2 * Math.PI / 180);
var y4 = rs * Math.sin( degree2 * Math.PI / 180);

   ctx.beginPath();
   ctx.moveTo(cx+x1, cy+y1);
   ctx.lineTo(cx+x2, cy+y2);
   ctx.lineTo(cx+x3, cy+y3);
   ctx.lineTo(cx+x4, cy+y4);
   ctx.closePath();
   ctx.fill();

   poly_x[rad_i*20 + sector_i] = new Array(cx+x1,cx+x2,cx+x3,cx+x4);
   poly_y[rad_i*20 + sector_i] = new Array(cy+y1,cy+y2,cy+y3,cy+y4);
}
//////////////////////////////////////////////////////////
function drawCircle(ctx, x, y, r, fillStyle, save_poly) {
   var x1,y1;
   var degree1,poly_num;

   ctx.fillStyle = fillStyle;
   ctx.beginPath();
   ctx.moveTo(x+r, y);

 if (save_poly) {
   if (r == rad_to[0]) {
     poly_num = poly_num0;
   }
   if (r == rad_to[1]) {
     poly_num = poly_num1;
   }

   poly_x[poly_num] = new Array(x+r);
   poly_y[poly_num] = new Array(y);
 }

  for (i=0; i<20; i=i+1) {
   degree1 = i * deg + deg/2;
   x1 = r * Math.cos( degree1 * Math.PI / 180);
   y1 = r * Math.sin( degree1 * Math.PI / 180);
   ctx.lineTo(x+x1, y+y1);
   if (save_poly) {
     poly_x[poly_num][i+1] = x+x1;
     poly_y[poly_num][i+1] = y+y1;
   }
  }

   ctx.closePath();
   ctx.fill();
}
//////////////////////////////////////////////////////////
function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
}
//////////////////////////////////////////////////////////
function darts_board_init(width,height, board_x,board_y, radius, target) {
	if($('#darts_board')) $('#darts_board').remove();
   $(target).append('<canvas id="darts_board" width="' + width + '" height="' + height + '" style="position: relative; border: 1px dotted #EEEEEE;">Your browser is currently unsupported canvas</canvas>');
   cx = board_x;
   cy = board_y;
   darts_board_width = width;
   darts_board_height = height;
	darts_board_radius = radius;
	darts_board_x = board_x;
	darts_board_y = board_y;
   rad_from = new Array(0,26/350*radius,50/350*radius,198/350*radius,230/350*radius,320/350*radius);
   rad_to = new Array(Math.round(22/350*radius),Math.round(47/350*radius),195/350*radius,227/350*radius,317/350*radius,350/350*radius);
   canvas = document.getElementById("darts_board");
   ctx = canvas.getContext("2d");

//   canvas_offset = findPos(canvas);
   canvas.addEventListener('mousemove', ev_mousemove, false);
   canvas.addEventListener('mousedown', ev_mouseclick, false);
   var R1,R2;



	drawBoard();
}

function drawBoard() {
   canvas = document.getElementById("darts_board");
   ctx = canvas.getContext("2d");

   ctx.fillStyle = "rgba(30,30,30,1)";
   ctx.fillRect(0, 0, darts_board_width, darts_board_height);
   ctx.globalAlpha = 1.0;
 
   ctx.translate(0, 0); 
   ctx.save();
 for (i=0;i<20;i=i+2) {
   drawSector(ctx,"red",i, 5);
   drawSector(ctx,"green",i+1, 5);
 }

 for (i=0;i<20;i=i+2) {
   drawSector(ctx,"black",i, 4);
   drawSector(ctx,"rgba(200,200,200,1)",i+1, 4);
 }

 for (i=0;i<20;i=i+2) {
   drawSector(ctx,"red",i, 3);
   drawSector(ctx,"green",i+1, 3);
 }

 for (i=0;i<20;i=i+2) {
   drawSector(ctx,"black",i, 2);
   drawSector(ctx,"rgba(200,200,200,1)",i+1, 2);
 }

   drawCircle(ctx, cx, cy, rad_to[1], "green", 1);
   drawCircle(ctx, cx, cy, rad_from[1]-1, "black", 0);
   drawCircle(ctx, cx, cy, rad_to[0], "red", 1);

   ctx.fillStyle = "white";
   ctx.font = 30/350*darts_board_radius + "pt Arial";

 var r = 372/350*darts_board_radius;
 var degree1;
 for (i=0; i<20; i=i+1) {
   degree1 = i * deg + deg;
   x1 = r * Math.cos( degree1 * Math.PI / 180);
   y1 = r * Math.sin( degree1 * Math.PI / 180);
   ctx.fillText(nums[i], cx+x1-(20/350*darts_board_radius), cy+y1+(15/350*darts_board_radius));
 }
   ctx.restore();
	
}
//////////////////////////////////////////////////////////
function get_mouse_pos(e) {
  var mouseX, mouseY;

    if(e.offsetX) {
        mouseX = e.offsetX;
        mouseY = e.offsetY;
    }
    else if(e.layerX) {
        mouseX = e.layerX;
        mouseY = e.layerY;
    }
  return {x: mouseX, y: mouseY};
}
//////////////////////////////////////////////////////////
function print_target(pos_x, pos_y, rad, num) {
   ctx.fillStyle = "black";
   ctx.fillRect(pos_x, pos_y, 100, 20);
   ctx.font = "12pt Calibri";
   ctx.fillStyle = "white";
   ctx.fillText(rad + " / " + num, pos_x+5, pos_y+15);
}
//////////////////////////////////////////////////////////
function get_target(x, y) {
  var rad_selected = -1;
  var sector_selected = -1;
  var num_selected = 0;

  for (rad_i=2; rad_i<=5; rad_i++) {
    for (sector_i=0; sector_i<=19; sector_i++) {
      if (pointInPolygon(x, y, sector_i, rad_i)) {
        rad_selected = rad_i;
        sector_selected = sector_i;
        num_selected = nums[sector_selected];
        break;
      }
    }
  }

  if (rad_selected == -1) {
      if (pointInPolygon(x, y, null, 1)) {
        rad_selected = 1;
        //sector_selected = -1;
        //num_selected = 0;
      }
      if (pointInPolygon(x, y, null, 0)) {
        rad_selected = 0;
        //sector_selected = -1;
        //num_selected = 0;
      }
  }

  return {rad: rad_selected, num:num_selected};
}
//////////////////////////////////////////////////////////
function ev_mousemove(ev) {
  var cursor = get_mouse_pos(ev);
  var target = get_target(cursor.x, cursor.y);
  print_target(15, 15, target.rad, target.num);
}
//////////////////////////////////////////////////////////
function ev_mouseclick(ev) {
  var cursor = get_mouse_pos(ev);
  var target = get_target(cursor.x, cursor.y);

  if (cursor.x <= darts_board_width && cursor.y <= darts_board_height) {
    print_target(15, 35, target.rad, target.num);
		
    eval(darts_hook + "(" + target.rad + "," + target.num + ","+ cursor.x+","+ cursor.y+");");

    //ajax request here for save action
  }
}
//////////////////////////////////////////////////////////
function default_hook(rad, num) {
   alert('No active game; ' + rad + "/" + num);
}
//////////////////////////////////////////////////////////
function drawPlayersMask() {
	drawBoard();

		var canvas = document.getElementById("darts_board");
		var ctx = canvas.getContext("2d");
		ctx.save();
		var numplayers = new Array();
		for(var i=0;i<players.length;i++) {
			if((player_lifes[i] - player_lifes_killed[i])>0 && players[i].checked)
				numplayers[numplayers.length] = players[i].num;
		}
		for (i=0;i<20;i=i+1) {
			if(gamestarted && !numplayers.inArray(nums[i]) || !gamestarted && !selectedNums.inArray(nums[i]) || gamestarted && 	((blind_rounds_count-current_round_num)>=0) ) {
				drawSector(ctx,"rgba(66,66,66,0.8)",i, 5);
				drawSector(ctx,"rgba(66,66,66,0.8)",i, 4);
				drawSector(ctx,"rgba(66,66,66,0.8)",i, 3);
				drawSector(ctx,"rgba(66,66,66,0.8)",i, 2);
			} else {
			if((blind_rounds_count-current_round_num)<0) {
				if(gamestarted) {
					var r = 372/350*(darts_board_radius-1/4*darts_board_radius);
					var degree1;
					degree1 = i * deg + deg;
					x1 = r * Math.cos( degree1 * Math.PI / 180);
					y1 = r * Math.sin( degree1 * Math.PI / 180);
					ind = get_player_by_num(nums[i]);
					ctx.fillStyle = "red";
					ctx.font = 30/350*darts_board_radius + "pt Arial";
					ctx.fillText('('+(player_lifes[ind]-player_lifes_killed[ind])+')', cx+x1-(20/350*(darts_board_radius)), cy+y1+(20/350*(darts_board_radius)));
					ctx.fillStyle = "red";
					ctx.font = 13/350*darts_board_radius + "pt Arial bold";
					ctx.fillText(players[ind].name, cx+x1-(25/350*(darts_board_radius)), cy+y1-(20/350*(darts_board_radius)));
				}
			}
			}
			
		}
		ctx.restore();
	drawDarts();
}

var dartsArr = Array();

function addDart(point,width) {
	if(dartsArr.length == dart_num_per_player) dartsArr = Array();
	dartsArr[dartsArr.length] = {point:point,width:width};
}

function drawDarts() {
	var canvas = document.getElementById("darts_board");
	var ctx = canvas.getContext("2d");
	for(var i=0;i<dartsArr.length;i++) {
		j = i % 3;
		ctx.drawImage(dartImages[j].image, dartsArr[i].point.x-dartImages[j].xscale*dartsArr[i].width, dartsArr[i].point.y-dartImages[j].yscale*dartsArr[i].width, dartsArr[i].width, dartsArr[i].width);
	}
}
